package com.nineclock.common.aliyun.sms;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
@PropertySource(value = "classpath:sms.properties", encoding = "UTF-8")
public class SmsUtils {

    @Value("${aliyun.sms.appcode}")
    private String appCode;

    /**
     * 生成随机的6位验证码
     * @return
     */
    public String generateCheckCode(){

        int flag = new Random().nextInt(999999);
        if (flag < 100000)
        {
            flag += 100000;
        }
        return Integer.valueOf(flag).toString();

    }

    /**
     * 发送短信验证码
     * @param mobile  接收验证码的手机号
     * @param code  短信验证码
     */
    public boolean sendSms(String mobile,String code) {

        /***以下内容固定，不要改变***/
        String apiUrl = "https://gyytz.market.alicloudapi.com/sms/smsSend";
        Map<String, Object> formMap = new HashMap<String, Object>();
        formMap.put("mobile", mobile);
        formMap.put("param", "**code**:"+code+",**minute**:5");
        //使用默认smsSignId即可
        formMap.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        //使用默认templateId即可
        formMap.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        try {
            String result = HttpRequest.post(apiUrl)
                    //头信息，多个头信息多次调用此方法即可
                    .header(Header.AUTHORIZATION, "APPCODE " + appCode)
                    .form(formMap)//表单内容
                    .timeout(20000)//超时，毫秒
                    .execute().body();
            Map<String,String> map = JSON.parseObject(result, Map.class);
            return "0".equals(map.get("code")) ? true : false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }
}